<?php

class ConsumuriForm extends WrapperForm
{
    const NAME = 'consumuri';

    protected function _prepareFormSchema(array &$taintedValues)
    {
        $newValues = array();
        $count = 0;
        foreach ($taintedValues as $apId => $consumuri)
        {
            if (!is_array($consumuri))
            {
                $newValues[$apId] = $consumuri;
                continue;
            }

            foreach ($consumuri as $criteriuId => $valoare)
            {
                $wrapperForm = new BaseForm();
                $consumForm = new ConsumForm();
                $wrapperForm->embedForm($consumForm);
                $this->embedForm($count, $wrapperForm);

                $consumForm->useFields(array(ConsumForm::APARTAMENT_ID, ConsumForm::CRITERIU_ID, ConsumForm::VALOARE));
                $newValues[$count++] = array(
                    $consumForm->getFormName()  => array(
                        ConsumForm::APARTAMENT_ID   => $apId,
                        ConsumForm::CRITERIU_ID     => $criteriuId,
                        ConsumForm::VALOARE         => $valoare,
                    )
                );
            }
        }

        // overwrite original values
        $taintedValues = $newValues;
    }

    protected function _afterSave()
    {
        // save ConsumForm embedded forms (this process is not handled by SymfonyForms)

        /* @var $wrapperForm BaseForm */
        foreach ($this->getEmbeddedForms() as $index => $wrapperForm)
        {
            /* @var $consumForm ConsumForm */
            /* @var $consumObject Consum */

            $consumForm = current($wrapperForm->getEmbeddedForms());
            if ( $consumObject = $consumForm->saveObject( $this->values[$index][$consumForm->getName()] ) )
            {
                $this->responseData[] = array(
                    ConsumForm::APARTAMENT_ID   => $consumObject->getApartamentId(),
                    ConsumForm::CRITERIU_ID     => $consumObject->getCriteriuId(),
                    ConsumForm::VALOARE         => $consumObject->getValoare(true),
                );
            }
        }
    }

}
